package com.sun.entitys;

import com.sun.dto.users.LoginUserDetails;
import jakarta.persistence.PrePersist;
import jakarta.persistence.PreUpdate;
import org.springframework.security.core.context.SecurityContextHolder;

import java.time.LocalDateTime;

/**
 * MP自动填充Handler
 *
 * @Author whsunchunbo@qq.com
 * @CreateTime 2025/9/9 21:49
 */
public class CreateAndUpadteEvent {
    @PrePersist
    public void prePersist(BaseEntity entity) {
        System.out.println("prePersist");
        entity.setCreateTime(LocalDateTime.now());
        LoginUserDetails userDetails = (LoginUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        entity.setCreaterId(userDetails.getUserId());
        entity.setCreaterName(userDetails.getName());
        entity.setUpdateTime(LocalDateTime.now());
        entity.setUpdaterId(userDetails.getUserId());
        entity.setUpdaterName(userDetails.getName());
        entity.setDeleted(0L);
        entity.setEnabled(true);

    }
    @PreUpdate
    public void preUpdate(BaseEntity entity) {
        entity.setUpdateTime(LocalDateTime.now());
        LoginUserDetails userDetails = (LoginUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        entity.setUpdaterId(userDetails.getUserId());
        entity.setUpdaterName(userDetails.getName());
        System.out.println("preUpdate");
    }
}
